package org.springframework.learn.beans.data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * Description
 * Copyright © 启明星辰 版权所有
 *
 * @author chenjiquan
 * @date 2023-11-16
 */
@Component
public class OuterClass {

	private final Car car;
	private final InnerClass innerClass;

	@Autowired
	public OuterClass(Car car) {
		this.car = car;
		innerClass = new InnerClass();
	}

	public Car getCar() {
		return car;
	}

	public OuterClass getOuterClass() throws IllegalAccessException, NoSuchFieldException {
		// 从内部类中获取外部类的引用
		Field outerField  = innerClass.getClass().getDeclaredField("this$0");
		outerField.setAccessible(true);
		// 内部类中的外部类（所以内部类可以调用外部类的方法和属性，就是通过this$0去调用的）
		OuterClass outer = (OuterClass) outerField.get(innerClass);
		return outer;
	}

	public void test() {
		System.out.println(getCar());
		System.out.println("-----------------------");
		innerClass.test();
	}

	class InnerClass {
		private void test() {
			System.out.println(getCar());
		}
	}
}
